<?php

namespace App\Admin\Controllers;

use Encore\Admin\Form;
use Encore\Admin\Layout\Column;
use Encore\Admin\Layout\Row;
use Encore\Admin\Widgets\Box;
use App\Http\Controllers\Controller;
//use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use Encore\Admin\Tree;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Auth\Database\Administrator;
use Illuminate\Http\Request;
use App\Models\Teaching_plan;
use Illuminate\Support\Facades\DB;
class Teaching_planController extends Controller {
    use ModelForm;

    /**
     * 重定向至 typedEntering
     */
    public function index(Content $content) {
		return redirect("/admin/teaching_plan/type/teaching");
    }

	/**
	 * [新的教学计划入口]
	 */
	public function typedEntering($type,Content $content) {
		return $content->header(trans('admin.'.$type.'_plan.header'))
			->description(trans('admin.tree'))
			->row(function (Row $row)use($type) {
	            $row->column(6, $this->treeView($type)->render());
	            $row->column(6, function (Column $column)use($type) {
	            	$form = new \Encore\Admin\Widgets\Form();
	            	$form->action(admin_base_path('teaching_plan'));
	            	$form->select('parent_id', trans('admin.'.$type.'_plan.parent_id'))
						->options(Teaching_plan::ethanSelectOpts(['type'=>$type]))
						->addElementLabelClass('must-input');
		            $form->text('title', trans('admin.'.$type.'_plan.title'))
						->rules('required')
						->addElementLabelClass('must-input');
		            $form->text('remark', trans('admin.'.$type.'_plan.remark'));
					$form->hidden('type')->default($type);
		            $column->append((new Box(trans('admin.new'), $form))->style('success'));
	            });
	        });
	}

    /**
     * Redirect to edit page.
     *
     * @param int $id
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function show($type,$id) {
		return redirect("/admin/teaching_plan/type/".$type."/".$id."/edit");
    }

    /**
     * @return \Encore\Admin\Tree
     */
    protected function treeView($type) {
        return Teaching_plan::tree(function (Tree $tree)use($type) {
			$tree->query(function ($query)use($type) {
		        return $query->where("type",$type);
		    })->branch(function ($branch) {
                $payload = "<strong>{$branch['title']}</strong><span style='margin-left:50px;'>{$branch['remark']}</span>";
                return $payload;
            })->disableCreate();
        });
    }

    public function edit($type,$id,Content $content) {
		return $content
            ->header(trans('admin.'.$type.'_plan.header'))
            ->description(trans('admin.edit'))
            ->row($this->editform($type,$id)->edit($id));
    }

	public function update($type,$id,Request $request) {
		$data = [
			'parent_id' => $request->get('parent_id'),
			'title' => $request->get('title'),
			'remark' => $request->get('remark')
		];
		$res = Teaching_plan::where(['id'=>$id])->update($data);
		return redirect("/admin/teaching_plan/type/".$type);
	}

    /**
     * Make a form builder.
     *
     * @return Form
     */
    public function editform($type,$id) {
        $form = new Form(new Teaching_plan());
        $form->display('id', 'ID');
        $form->select('parent_id',trans('admin.'.$type.'_plan.parent_id'))
			->options(Teaching_plan::ethanSelectOpts([['type','=',$type],['id','<>',$id]]))
			->addElementLabelClass('must-input');
        $form->text('title',trans('admin.'.$type.'_plan.title'))->rules('required')->addElementLabelClass('must-input');
        $form->text('remark',trans('admin.'.$type.'_plan.remark'));
        return $form;
    }

	public function store(Request $request) {
		$data = [
			'parent_id' => $request['parent_id'],
			'title' => $request['title'],
			'remark' => $request['remark'],
			'type' => $request['type'],
		];
		$res = Teaching_plan::insert($data);
		return redirect("/admin/teaching_plan/type/".$data['type']);
	}

	public function destroy($type,$id) {
		$ids = $this->getAllSubNodesId($id);
		Teaching_plan::whereIn('id',$ids)->delete();
	}
	private function getAllSubNodesId($id,$ids=[]) {
		$ids[] = $id;
		$sub = Teaching_plan::where('parent_id','=',$id)->pluck("id")->toArray();
		foreach($sub as $v){
			$ids = $this->getAllSubNodesId($v,$ids);
		}
		$ids = array_merge(array_filter(array_unique($ids)));
		return $ids;
	}

	public function reOrder($type,Request $request) {
		$param = json_decode($request->get("_order"),true);
		DB::beginTransaction();
		try {
			foreach($param as $v){
				DB::table("teaching_plans")->where('id','=',$v['id'])->update(["parent_id"=>0]);
				if(array_key_exists("children",$v)){
					$this->resetOrder($v);
				}
			}
			DB::commit();
		} catch (\Exception $e) {
			DB::rollback();
			print_r("[ Error: ]-----------------------------------\n");
			print_r($e->getMessage()."\n");
			print_r("---------------------------------------------\n");
		}
		print_r("[ SUCCESS ]*****************************************\n");
	}
	private function resetOrder($data) {
		foreach($data['children'] as $child){
			DB::table("teaching_plans")->where('id','=',$child['id'])->update(["parent_id"=>$data['id']]);
			if(array_key_exists("children",$child)){
				$this->resetOrder($child);
			}
		}
	}


}
